<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格占位 -->
      <el-table
      class="treeTable"
        :data="catelist"
        style="width: 100%"
        row-key="id"
        border
        show-header
        doLayout
        lazy
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <!-- <el-table-column type="index" :index="indexMethod" label="#"> </el-table-column> -->
        <el-table-column
          prop="name"
          label="分类名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="level"
          label="分类等级"
          width="180">
          <template slot-scope="scope">
            <el-tag size="mini" v-if="scope.row.level == 1">一级</el-tag>
            <el-tag size="mini" v-else-if="scope.row.level == 2" type="success">二级</el-tag>
            <el-tag size="mini" v-else-if="scope.row.level == 3" type="warning">三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="操作"
          width="180">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeCateById(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类页面 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="60%"
      @close="addCateDialogClosed"
    >
    <!-- 内容主体区 -->
    <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="80px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="addCateForm.name"></el-input>
      </el-form-item>
      <!-- options指定数据源 -->
      <!-- props用来指定配置对象 -->
      <el-form-item label="父级分类">
        <el-cascader
          v-model="selectKeys"
          :options="parentCateList"
          :props="{ expandTrigger: 'hover',
            value: 'id',
            label: 'name',
            children: 'children'
          }"
          @change="parentCateChange"
          change-on-select
          clearable></el-cascader>
      </el-form-item>
    </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改分类页面 -->
    <el-dialog
      title="添加分类"
      :visible.sync="editCateDialogVisible"
      width="60%"
      @close="editCateDialogClosed"
    >
    <!-- 内容主体区 -->
    <el-form :model="editCateForm" :rules="editCateFormRules" ref="editCateFormRef" label-width="80px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="editCateForm.name"></el-input>
      </el-form-item>
    </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCateList()
  },
  mounted() {
  },
  data() {
    return {
      // 商品分类的数据，默认为空
      catelist: [],
      // 查询条件
      queryInfo: {
        type: 2,
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10
      },
      addCateDialogVisible: false,
      total: 0,
      // 添加分类的表单数据对象
      addCateForm: {
        // 默认添加父级分类名称
        id: 0,
        name: '',
        parent_id: null,
        level: 1
      },
      addCateFormRules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      // 父级分类列表
      parentCateList: [],
      // 选中的父级分类ID数组
      selectKeys: [],
      editCateDialogVisible: false,
      editCateForm: [],
      editCateFormRules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$axios.get('/product-categories/selectProduct', {
        params: this.queryInfo
      })
      if (res.code !== 200) {
        return this.$message.error('获取商品分类失败！  ')
      }
      // 把数据列表，赋值给categories
      this.catelist = res.data.prolist
      // console.log(this.catelist)
      // 为总数据条数赋值
      this.total = res.data.total
    },
    // 监听pagesize改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    // 监听pagenum的改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，展示添加分类的对话框
    showAddCateDialog() {
      // 先获取父级分类的数据
      this.getParentCateList()
      // 在展示出对话框
      this.addCateDialogVisible = true
    },
    // 获取父级分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$axios.get('/product-categories/selectProduct',
      { params: { type: 1, pagenum: 1, pagesize: 10 } })
      if (res.code !== 200) {
       return this.$message.error('获取数据失败！ ')
      }
      this.parentCateList = res.data.prolist
    },
    parentCateChange() {
      // 如果selectKeys数组中的length > 0，证明选中父级分类
      // 反之就没有选中任何父级分类
      if (this.selectKeys.length > 0) {
        // 父级分类的ID
        this.addCateForm.parent_id = this.selectKeys[this.selectKeys.length - 1]
        // 为当前分类的等级赋值
        this.addCateForm.level = this.selectKeys.length + 1
      } else {
        this.addCateForm.parent_id = 0
        // 为当前分类的等级赋值
        this.addCateForm.level = 1
      }
    },
    // 点击按钮添加新的分类
    addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.post('/product-categories/add', this.addCateForm)
        console.log(res)
        if (res.code !== 200) {
        return this.$message.error('添加分类失败！ ')
      }
        this.$message.success('添加分类成功！ ')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    // 监视对话框的关闭事件，重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectKeys = []
      this.addCateForm.parent_id = null
      this.addCateForm.level = 0
    },
    // 删除
    async removeCateById(id) {
      // 弹框提示是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该分类，是否继续？', '删除分类', {
        confirmButtonText: '',
        cancelButtonText: '',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
            return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$axios.delete('/product-categories/delete/' + id)
      if (res.code !== 200) {
          return this.$message.error('删除失败！请先删除下级的所有分类')
      }
        this.$message.success('删除成功！ ')
        this.getCateList()
    },
    editCateDialogClosed() {
      this.$refs.editCateFormRef.resetFields()
    },
    // 展示编辑修改页面
    async showEditDialog(id) {
      const { data: res } = await this.$axios.get('/product-categories/selectById/' + id)
      if (res.code !== 200) {
          return this.$message.error('查询用户失败！ ')
      }
      this.editCateForm = res.data.prolist[0]
      this.editCateDialogVisible = true
    },
    // 提交修改
    editCate() {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.put('/product-categories/update/' + this.editCateForm.id, {
          name: this.editCateForm.name,
          parentId: this.editCateForm.parentId,
          level: this.editCateForm.level
          })
        if (res.code !== 200) {
          return this.$message.error('更新信息失败！ ')
        }
        // 关闭修改窗口
        this.editCateDialogVisible = false
        // 更新列表
        this.getCateList()
        // 提示修改信息成功
        this.$message.success('更新信息成功！ ')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>
